package com.corner.model.oss;


import android.content.Context;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.sdk.android.oss.OSSService;
import com.alibaba.sdk.android.oss.OSSServiceProvider;
import com.alibaba.sdk.android.oss.model.AuthenticationType;
import com.alibaba.sdk.android.oss.model.ClientConfiguration;
import com.alibaba.sdk.android.oss.model.OSSException;
import com.alibaba.sdk.android.oss.model.TokenGenerator;
import com.alibaba.sdk.android.oss.storage.OSSBucket;
import com.alibaba.sdk.android.oss.storage.OSSFile;
import com.alibaba.sdk.android.oss.util.OSSToolKit;
import com.corner.model.cornerservice.domain.CloudFile;
import com.corner.model.cornerservice.domain.Info;
import com.corner.model.cornerservice.service.Service;
import com.corner.model.cornerservice.service.exception.BaseException;

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2015/8/16，23.14.
 * 描述：
 */
public class OSSManager {

    private static OSSService ossService;
    private static OSSBucket cornerBucket;
    private static String accessKey = "4dLHbWOytiRpT1ta";
    private static String secretKey = "GtrDbE8ZKk2lMf80XaPUMA1njnIGhE";

    public static void init(Context context) {
        ossService = OSSServiceProvider.getService();
        ossService.setApplicationContext(context);
        ossService.setGlobalDefaultHostId("oss-cn-beijing.aliyuncs.com");
        ossService.setAuthenticationType(AuthenticationType.ORIGIN_AKSK);
        ossService.setGlobalDefaultTokenGenerator(new TokenGenerator() {
            @Override
            public String generateToken(String httpMethod, String md5, String type, String date, String ossHeaders,
                                        String resource) {
                String content = httpMethod + "\n" + md5 + "\n" + type + "\n" + date
                        + "\n" + ossHeaders + resource;
                return OSSToolKit.generateToken(accessKey, secretKey, content);
            }
        });

        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectTimeout(15 * 1000); // 设置建连超时时间，默认为30s
        conf.setSocketTimeout(15 * 1000); // 设置socket超时时间，默认为30s
        conf.setMaxConnections(50); // 设置全局最大并发连接数，默认为50个
        conf.setMaxConcurrentTaskNum(10); // 设置全局最大并发任务数，默认10个
        ossService.setClientConfiguration(conf);
        cornerBucket = ossService.getOssBucket("corner");
        cornerBucket.setBucketHostId("oss-cn-beijing.aliyuncs.com");
    }

    public static CloudFile upload(String path, float scale[]) throws BaseException, FileNotFoundException, OSSException {
        OSSFile ossFile = ossService.getOssFile(cornerBucket, String.valueOf((path + System.currentTimeMillis()).hashCode()));
        ossFile.setUploadFilePath(path, "img"); // 指明需要上传的文件的路径，和文件内容类型，如果文件不存在将抛出异常
        ossFile.enableUploadCheckMd5sum(); // 开启上传md5校验
        ossFile.upload(); // 上传失败将会抛出异常

        CloudFile cloudFile = new CloudFile();
        cloudFile.setFileUrl(ossFile.getResourceURL());
        cloudFile.setObjectKey(ossFile.getObjectKey());
        cloudFile.setBucketName(ossFile.getBucketName());
        HashMap<String, Object> meta = new HashMap<>();
        meta.put(Info.LEFT_SCALE, scale[0]);
        meta.put(Info.TOP_SCALE, scale[1]);
        meta.put(Info.RIGHT_SCALE, scale[2]);
        meta.put(Info.BOTTOM_SCALE, scale[3]);
        cloudFile.setMeta(new JSONObject(meta).toJSONString());
        return cloudFile;
    }

    public static CloudFile upload(String path) throws FileNotFoundException, OSSException, BaseException {
        OSSFile ossFile = ossService.getOssFile(cornerBucket, String.valueOf((path + System.currentTimeMillis()).hashCode()));
        ossFile.setUploadFilePath(path, "file"); // 指明需要上传的文件的路径，和文件内容类型，如果文件不存在将抛出异常
        ossFile.enableUploadCheckMd5sum(); // 开启上传md5校验
        ossFile.upload(); // 上传失败将会抛出异常

        CloudFile cloudFile = new CloudFile();
        cloudFile.setFileUrl(ossFile.getResourceURL());
        cloudFile.setObjectKey(ossFile.getObjectKey());
        cloudFile.setBucketName(ossFile.getBucketName());
        return cloudFile;
    }

    public static void upload(String path, String objectKey, final SaveCallback saveCallBack) throws FileNotFoundException {
        final OSSFile ossFile = ossService.getOssFile(cornerBucket, objectKey);
        ossFile.setUploadFilePath(path, "file"); // 指明需要上传的文件的路径，和文件内容类型，如果文件不存在将抛出异常
        ossFile.enableUploadCheckMd5sum(); // 开启上传md5校验
        ossFile.uploadInBackground(new com.alibaba.sdk.android.oss.callback.SaveCallback() {
            @Override
            public void onSuccess(String s) {
                CloudFile cloudFile = new CloudFile();
                cloudFile.setFileUrl(ossFile.getResourceURL());
                cloudFile.setObjectKey(ossFile.getObjectKey());
                cloudFile.setBucketName(ossFile.getBucketName());
                saveCallBack.onSuccess(cloudFile);
            }
            @Override
            public void onProgress(String s, int i, int i1) {
                saveCallBack.onProgress(s, i, i1);
            }

            @Override
            public void onFailure(String s, OSSException e) {
                saveCallBack.onFailure(e);
            }
        }); // 上传失败将会抛出异常
    }

    public interface SaveCallback {
        void onSuccess(CloudFile cloudFile);

        void onProgress(String objectKey, int byteCount, int totalSize);

        void onFailure(Throwable throwable);
    }
}
